from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
from waveapi import robot_abstract
from waveapi import simplejson as json

import string
import logging
import urllib

def AddGadget(properties, context):

	root_wavelet = context.GetRootWavelet()
	root_blip = context.GetBlipById(root_wavelet.GetRootBlipId()) 
	wavetype = string.lower(root_blip.GetDocument().GetText()[0])

	if wavetype == 'a':
		waveid = context.GetWaves()[0].GetId()

		gadget_arguments = {'waveid' : waveid}
		gadget_address = 'http://pgch.co.uk/gadgets/debatewise.Admin.xml'
		debatewise_gadget = document.Gadget(gadget_address, gadget_arguments)

		root_blip.GetDocument().AppendElement(debatewise_gadget)

	if wavetype == 't':
		waveid = context.GetWaves()[0].GetId()
		gadget_arguments = {'waveid' : waveid}
		googlecode_prefix = 'http://debatewave.googlecode.com/svn/trunk/gadgets'
		gadget_address = googlecode_prefix + '/participantAdder-test.xml'
		debatewise_gadget = document.Gadget( gadget_address, gadget_arguments )

		root_blip.GetDocument().AppendElement(debatewise_gadget)

def GadgetEventHandler(properties, context):

	# get the data from the current wave and its resident gadget
	root_wavelet = context.GetRootWavelet()
	root_blip = context.GetBlipById(root_wavelet.GetRootBlipId())   

	debatewise_gadget = [x for x in root_blip.GetElements().values() if x.type == document.ELEMENT_TYPE.GADGET][0] 

	# make sure we are responding to a legitimate event, not some other blip changes
	if int(debatewise_gadget.get('requesttype', '0')) == 1:

		gadget_addresses = ['http://pgch.co.uk/gadgets/debatewise.Admin.xml','http://pgch.co.uk/gadgets/debatewise.Index.xml','http://pgch.co.uk/gadgets/debatewise.Debate.xml','http://pgch.co.uk/gadgets/debatewise.Point.xml']
		gadget_address = debatewise_gadget.get('url')
		new_gadget_address = gadget_addresses[gadget_addresses.index(gadget_address) + 1]
		new_wave_titles = ["Debatewise Admin Gadget","Debatewise: Index of debates","Debatewise: Debate","Debatewise: Point"]
		new_wave_title = new_wave_titles[gadget_addresses.index(gadget_address) + 1]
		
		next_content_id = debatewise_gadget.get('nextcontentid')
		new_content = debatewise_gadget.get('newcontent')
		transaction_id = debatewise_gadget.get('transactionid')
		participants = debatewise_gadget.get('participants').split(',')

		# TODO: this test should be done by parsing the url data into json before comparison! 
		#if urllib.urlopen('http://dan-debatewise.appspot.com/debate/exchange/get?key='+next_content_id+'&waveid='+transaction_id+'&userid=robot').read()=='{"error": "Not found"}':

		# Get the values for the new wave gadget's content
		# to do...
		# Query the url to insert that content
		
		#urllib.urlopen('http://dan-debatewise.appspot.com/debate/exchange/add?key='+next_content_id+'&waveid='+transaction_id+'&userid=robot').read()

		bot_address = 'pgc-debatewise@appspot.com' 
		participants.append(bot_address)

		logging.debug(participants)

		# create a wave
		new_wave = robot_abstract.NewWave(context, participants)
		new_wave.SetTitle(new_wave_title)
		
		# add a gadget to the new wave
		gadget_arguments = {'contentid' : next_content_id,'newcontent' : new_content}
		new_gadget = document.Gadget(new_gadget_address, gadget_arguments)

		new_root_blip = context.GetBlipById(new_wave.GetRootBlipId())
		new_root_blip.GetDocument().AppendElement(new_gadget)

		# return the new waveId to the current gadget
		debatewise_gadget.SubmitDelta({'requesttype' : 0})
		debatewise_gadget.SubmitDelta({'transactionid' : 0})

	# now see if we have some more participants to add...
	new_participant_sets_count = int( debatewise_gadget.get( 'new_participant_sets_count', '0' ) )

	if new_participant_sets_count > 0:
		new_participants_sets_json = debatewise_gadget.get( 'new_participants_sets_json', '' )
		logging.debug( 'new_participants_sets_json:' + new_participants_sets_json )
		new_participants_sets = json.loads( new_participants_sets_json )
		logging.debug( 'new_participants_sets loaded into json:' + json.dumps( new_participants_sets ) )
		#new_participants_sets_debug_output = '\n'.join( [l.rstrip() for l in new_participants_sets.splitlines()] )

		root_wavelet.CreateBlip().GetDocument().SetText( "Found Participants Sets:" + json.dumps( new_participants_sets ) )
		for participant_set in new_participants_sets:
			logging.debug( 'my wave_id="' + waveid + '", participant_set["waveid"]="' + participant_set['waveid'] + '"' )
			if waveid == participant_set['waveid']:
				for participant in participant_set['participants'].split( ',' ):
					root_wavelet.AddParticipant( participant )
					root_wavelet.CreateBlip().GetDocument().SetText( "Added " + participant )
				#root_wavelet.CreateBlip().GetDocument().SetText( "Iterated set: wave_id=" + wave_id + ",participants=" + participants )
			#TODO: Clear from DB

		root_wavelet.CreateBlip().GetDocument().SetText( "Done iterating" )
		#TODO: Clear from shared state
		#debatewise_gadget.SubmitDelta( {'requesttype' : 0} )

	if debatewise_gadget.get('populated', '0') != 1:
		
		content_id = debatewise_gadget.get('contentid')
		new_content = debatewise_gadget.get('newcontent')
		
		if str(content_id)=='1':
			waveid = debatewise_gadget.GetId()
		else:
			waveid = "";
		
		urllib.urlopen(new_content+waveid).read()
		
		debatewise_gadget.SubmitDelta({'populated' : 1})
		
		
		
if __name__ == '__main__':
	debatewise_robot = robot.Robot('pgc-debatewise',
		image_url='http://pgc-debatewise.appspot.com/assets/icon.png',
		version='5',
		profile_url='http://pgc-debatewise.appspot.com/')

	debatewise_robot.RegisterHandler(events.WAVELET_SELF_ADDED, AddGadget)
	debatewise_robot.RegisterHandler(events.BLIP_SUBMITTED, GadgetEventHandler)
	debatewise_robot.Run()